/*******************************************************************************
 * Copyright 2011 See AUTHORS file.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package org.ruslan.kolobok.screen;

import org.ruslan.kolobok.Assets;
import org.ruslan.kolobok.OverlapTester;
import org.ruslan.kolobok.Settings;
import org.ruslan.kolobok.Utils;
import org.ruslan.kolobok.World;
import org.ruslan.kolobok.WorldRenderer;
import org.ruslan.kolobok.model.BarrelType;
import org.ruslan.kolobok.model.Projectile;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GLCommon;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.Ray;

public class GameScreen implements Screen {
	private static final int GAME_READY = 0;
	private static final int GAME_RUNNING = 1;
	private static final int GAME_PAUSED = 2;
	private static final int GAME_LEVEL_END = 3;
	private static final int GAME_OVER = 4;

	private static final int VIEWPORT_WIDTH = Gdx.graphics.getWidth();
	private static final int VIEWPORT_HEIGHT = Gdx.graphics.getHeight();

	private static final int PAUSE_WIDTH = 64;
	private static final int PAUSE_HEIGHT = 64;
	private static final int PAUSE_X = VIEWPORT_WIDTH - PAUSE_WIDTH;
	private static final int PAUSE_Y = VIEWPORT_HEIGHT - VIEWPORT_HEIGHT;

	private static final int RESUME_WIDTH = 192;
	private static final int RESUME_HEIGHT = 36;
	private static final int RESUME_X = (VIEWPORT_WIDTH - RESUME_WIDTH) / 2;
	private static final int RESUME_Y = 240;

	private static final int QUIT_WIDTH = 192;
	private static final int QUIT_HEIGHT = 36;
	private static final int QUIT_X = (VIEWPORT_WIDTH - QUIT_WIDTH) / 2;
	private static final int QUIT_Y = 204;

	private static final int READY_WIDTH = 192;
	private static final int READY_HEIGHT = 36;
	private static final int READY_X = (VIEWPORT_WIDTH - READY_WIDTH) / 2;
	private static final int READY_Y = (VIEWPORT_HEIGHT - READY_HEIGHT) / 2;

	// renderers
	private OrthographicCamera guiCam;
	private Vector3 touchPoint;
	private SpriteBatch batcher; // needed to draw HUD
	private WorldRenderer renderer;
	private ShapeRenderer shapeRenderer;
	private GLCommon gl;

	// game state
	private Game game;
	private int state;
	private World world;
	private int lastScore;

	// HUD
	private Rectangle pauseBounds;
	private Rectangle resumeBounds;
	private Rectangle quitBounds;
	private String scoreString;

	public GameScreen(Game game) {
		this.game = game;

		// setup renderer
		gl = Gdx.gl;
//		 gl.glEnable(GL10.GL_DEPTH_TEST);
//		 gl.glDepthFunc(GL10.GL_LESS);
		gl.glClearColor(0.5f, 0.5f, 1f, 0);
//		 gl.glEnable(GL10.GL_BLEND);
//		 gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE);

		batcher = new SpriteBatch();
		// batcher.enableBlending();
		world = new World();
		renderer = new WorldRenderer(world);

		// setup HUD camera
		guiCam = new OrthographicCamera(VIEWPORT_WIDTH, VIEWPORT_HEIGHT);
		guiCam.position.set(VIEWPORT_WIDTH / 2, VIEWPORT_HEIGHT / 2, 0);

		// set initial game state
		state = GAME_READY;
		lastScore = 0;

		// create HUD
		pauseBounds = new Rectangle(PAUSE_X, PAUSE_Y, PAUSE_WIDTH, PAUSE_HEIGHT);
		quitBounds = new Rectangle(RESUME_X, RESUME_Y, RESUME_WIDTH, RESUME_HEIGHT);
		resumeBounds = new Rectangle(QUIT_X, QUIT_Y, QUIT_WIDTH, QUIT_HEIGHT);
		scoreString = "SCORE: 0";

		// aux
		shapeRenderer = new ShapeRenderer();
		touchPoint = new Vector3();
	}

	private void update(float deltaTime) {
		if (deltaTime > 0.1f) {
			// game will slow down if hardware is too slow
			deltaTime = 0.1f;
		}

		switch (state) {
		case GAME_READY:
			updateReady();
			break;
		case GAME_RUNNING:
			updateRunning(deltaTime);
			break;
		case GAME_PAUSED:
			updatePaused();
			break;
		case GAME_LEVEL_END:
			updateLevelEnd();
			break;
		case GAME_OVER:
			updateGameOver();
			break;
		}
	}

	private void updateReady() {
		if (Gdx.input.justTouched()) {
			state = GAME_RUNNING;
		}
	}

	float x;
	float y;

	private void updateRunning(float deltaTime) {
		 float x = Gdx.input.getX();
		 float y = Gdx.input.getY();

//		if (Gdx.input.isKeyPressed(Input.Keys.DPAD_RIGHT)) {
//			x += deltaTime * 200;
//		} else {
//			for (int i = 0; i < 2; i++) {
//				if (Gdx.input.isTouched(i) && Gdx.input.getX() > Gdx.graphics.getWidth() * 0.80f) {
//					x += deltaTime * 200;
//				}
//			}
//		}
//
//		if (Gdx.input.isKeyPressed(Input.Keys.DPAD_LEFT)) {
//			x -= deltaTime * 200;
//		} else {
//			for (int i = 0; i < 2; i++) {
//				if (Gdx.input.isTouched(i) && Gdx.input.getX() < Gdx.graphics.getWidth() * 0.20f) {
//					x -= deltaTime * 200;
//				}
//			}
//		}
//
//		if (Gdx.input.isKeyPressed(Input.Keys.DPAD_UP)) {
//			y -= deltaTime * 200;
//		} else {
//			for (int i = 0; i < 2; i++) {
//				if (Gdx.input.isTouched(i) && Gdx.input.getY() < Gdx.graphics.getHeight() * 0.20f) {
//					y -= deltaTime * 200;
//				}
//			}
//		}
//
//		if (Gdx.input.isKeyPressed(Input.Keys.DPAD_DOWN)) {
//			y += deltaTime * 200;
//		} else {
//			for (int i = 0; i < 2; i++) {
//				if (Gdx.input.isTouched(i) && Gdx.input.getY() < Gdx.graphics.getHeight() * 0.20f) {
//					y += deltaTime * 200;
//				}
//			}
//		}

		touchPoint.set(x, y, 0);
		guiCam.unproject(touchPoint);

		if (Gdx.input.justTouched()) {
			if (OverlapTester.pointInRectangle(pauseBounds, touchPoint.x, touchPoint.y)) {
				Assets.playSound(Assets.clickSound);
				state = GAME_PAUSED;
				return;
			}

			// shoot
			Ray pickingRay = renderer.cam.getPickRay(x, y);
			// float width = 10;
			// float height = 10;

			Projectile projectile = new Projectile(Assets.hitType);// pickingRay.origin,
															// width, height);
			projectile.getPosition().set(pickingRay.origin);
			projectile.getVelocity().set(pickingRay.direction.cpy().mul(100000));
			world.projectiles.add(projectile);
		}

		world.update(deltaTime);

		// update scores
		if (world.score != lastScore) {
			lastScore = world.score;
			scoreString = "SCORE: " + lastScore;
		}
		if (world.state == World.WORLD_STATE_NEXT_LEVEL) {
			state = GAME_LEVEL_END;
		}
		if (world.state == World.WORLD_STATE_GAME_OVER) {
			state = GAME_OVER;
			if (lastScore >= Settings.highscores[4])
				scoreString = "NEW HIGHSCORE: " + lastScore;
			else
				scoreString = "SCORE: " + lastScore;
			Settings.addScore(lastScore);
			Settings.save();
		}
	}

	private void updatePaused() {
		if (Gdx.input.justTouched()) {
			guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));

			if (OverlapTester.pointInRectangle(resumeBounds, touchPoint.x, touchPoint.y)) {
				Assets.playSound(Assets.clickSound);
				state = GAME_RUNNING;
				return;
			}

			if (OverlapTester.pointInRectangle(quitBounds, touchPoint.x, touchPoint.y)) {
				Assets.playSound(Assets.clickSound);
				game.setScreen(new MainMenuScreen(game));
				return;
			}
		}
	}

	private void updateLevelEnd() {
		if (Gdx.input.justTouched()) {
			world = new World();
			renderer = new WorldRenderer(world);
			world.score = lastScore;
			state = GAME_READY;
		}
	}

	private void updateGameOver() {
		if (Gdx.input.justTouched()) {
			game.setScreen(new MainMenuScreen(game));
		}
	}

	private void drawHud(SpriteBatch batcher) {
		// draw HUD
		guiCam.update();
		batcher.setProjectionMatrix(guiCam.combined);
		// batcher.enableBlending();
		batcher.begin();
		switch (state) {
		case GAME_READY:
			drawReady();
			break;
		case GAME_RUNNING:
			drawRunning();
			break;
		case GAME_PAUSED:
			drawPaused();
			break;
		case GAME_LEVEL_END:
			drawLevelEnd();
			break;
		case GAME_OVER:
			drawGameOver();
			break;
		}
		batcher.end();
	}

	private void draw() {
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		// gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

		// draw the world
		renderer.render();

		drawHud(batcher);

		drawAux();
	}

	private void drawAux() {
		// draw AUX
		shapeRenderer.setProjectionMatrix(guiCam.combined);
		shapeRenderer.begin(ShapeType.Rectangle);
		if (state == GAME_RUNNING) {
			Utils.drawRect(shapeRenderer, pauseBounds, Color.RED);
		} else if (state == GAME_PAUSED) {
			Utils.drawRect(shapeRenderer, quitBounds, Color.GREEN);
			Utils.drawRect(shapeRenderer, resumeBounds, Color.BLUE);
		}
		shapeRenderer.end();

		// shapeRenderer.begin(ShapeType.FilledCircle);
		// shapeRenderer.setColor(Color.CYAN);
		// shapeRenderer.filledCircle(touchPoint.x, touchPoint.y, 10);
		// shapeRenderer.end();
	}

	private void drawReady() {
		batcher.draw(Assets.ready, READY_X, READY_Y, READY_WIDTH, READY_HEIGHT);
	}

	private void drawRunning() {
		batcher.draw(Assets.pause, PAUSE_X, PAUSE_Y, PAUSE_WIDTH, PAUSE_HEIGHT);
		Assets.font.draw(batcher, scoreString, 16, VIEWPORT_HEIGHT - 20);
		batcher.draw(Assets.crosshair, touchPoint.x - 16, touchPoint.y - 16, 32, 32);
	}

	private void drawPaused() {
		Utils.drawTextureRegion(batcher, Assets.resume, resumeBounds);
		Utils.drawTextureRegion(batcher, Assets.quit, quitBounds);
		Assets.font.draw(batcher, scoreString, 16, VIEWPORT_HEIGHT - 20);
	}

	private void drawLevelEnd() {
		String topText = "the princess is ...";
		String bottomText = "in another castle!";
		float topWidth = Assets.font.getBounds(topText).width;
		float bottomWidth = Assets.font.getBounds(bottomText).width;
		Assets.font.draw(batcher, topText, 160 - topWidth / 2, VIEWPORT_HEIGHT - 40);
		Assets.font.draw(batcher, bottomText, 160 - bottomWidth / 2, 40);
	}

	private void drawGameOver() {
		batcher.draw(Assets.gameOver, 160 - 160 / 2, 240 - 96 / 2, 160, 96);
		float scoreWidth = Assets.font.getBounds(scoreString).width;
		Assets.font.draw(batcher, scoreString, 160 - scoreWidth / 2, VIEWPORT_HEIGHT - 20);
	}

	@Override
	public void render(float delta) {
		update(delta);
		draw();
	}

	@Override
	public void resize(int width, int height) {
	}

	@Override
	public void show() {
	}

	@Override
	public void hide() {
	}

	@Override
	public void pause() {
		if (state == GAME_RUNNING) {
			state = GAME_PAUSED;
		}
	}

	@Override
	public void resume() {
	}

	@Override
	public void dispose() {
	}
}
